﻿/////////////////////////////////////////////////////////////////////////////////
//
// PlainText
// - Gets rid of unwanted formatting
// (C) Copyright Johan Åhlén 2009
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
// See the GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
//
// More info on PlainText website: http://plaintext.codeplex.com
//
/////////////////////////////////////////////////////////////////////////////////


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Linq;

namespace AdvantIQ.PlainText
{
    /// <summary>
    /// Provides user selectable options
    /// </summary>
    public partial class OptionsDlg : Form
    {
        /// <summary>
        /// Get's full path of this application
        /// </summary>
        internal static string AssemblyLocation
        {
            get
            {
                return Assembly.GetExecutingAssembly().Location;
            }
        }

        public OptionsDlg()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Initialises form
        /// </summary>
        private void InitForm()
        {
            // Populate hotkey dropdownlist
            HotKeyDpl.Items.Clear();
            foreach (char ch in MainWnd.AllowedHotKeys)
                HotKeyDpl.Items.Add(ch);
            for (int i = 0; i < HotKeyDpl.Items.Count; i++)
                if (((int)(char)(HotKeyDpl.Items[i])) == Properties.Settings.Default.HotkeyChar)
                {
                    HotKeyDpl.SelectedIndex = i;
                    break;
                }

            // Populate modifiers list
            ModifiersCbl.Items.Clear();
            foreach (string modifier in Enum.GetNames(typeof(NativeMethods.Modifiers)))
            {
                int modifierNumber = (int)(NativeMethods.Modifiers)Enum.Parse(typeof(NativeMethods.Modifiers), modifier);
                bool flag = (modifierNumber & Properties.Settings.Default.HotkeyModifiers) != 0;
                ModifiersCbl.Items.Add(modifier, flag);
            }

            // Set current value of autostart checkbox
            AutostartCbx.Checked = Autostart.IsAutoStartEnabled(MainWnd.AppKey, AssemblyLocation);

            // Show filters
            var allFilterIDs = Filter.GetAllFilterIDs();
            var enabledFilterIDs = Filter.GetEnabledFilterIDs();
            FiltersCbl.Items.Clear();
            foreach (var filterID in allFilterIDs)
            {
                FiltersCbl.Items.Add(filterID, enabledFilterIDs.Contains(filterID));
            }
        }

        /// <summary>
        /// OnLoad event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OptionsDlg_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        /// <summary>
        /// OK button event handler. Saves user selections.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKBtn_Click(object sender, EventArgs e)
        {
            // Retrieve hotkey
            char hotkey = HotKeyDpl.SelectedItem.ToString()[0];

            // Retrieve modifiers (as a bit mask)
            int modifiers = 0;
            for (int i = 0; i < ModifiersCbl.Items.Count; i++)
            {
                if (ModifiersCbl.GetItemChecked(i))
                {
                    NativeMethods.Modifiers modifier = (NativeMethods.Modifiers)Enum.Parse(typeof(NativeMethods.Modifiers), ModifiersCbl.Items[i].ToString());
                    modifiers += (int)modifier;
                }
            }

            // Check for invalid hotkey combination
            // - Must not contain Ctrl and V due to a conflict with regular paste function
            // - Must have at least one modifier
            // - Must not have only Shift as modifier
            if ((hotkey == 'V' && ((modifiers & (int)NativeMethods.Modifiers.Ctrl) != 0))
                || (modifiers == 0)
                || (modifiers == (int)NativeMethods.Modifiers.Shift))
            {
                MessageBox.Show(this, Properties.Resources.InvalidHotkeyStr, 
                    Properties.Resources.InvalidHotkeyCaptionStr, MessageBoxButtons.OK, 
                    MessageBoxIcon.Error);
                return;
            }

            // Save user selections
            Properties.Settings.Default.HotkeyChar = (int)hotkey;
            Properties.Settings.Default.HotkeyModifiers = modifiers;
            Properties.Settings.Default.Save();

            // Change autostart state
            bool autostartEnabled = Autostart.IsAutoStartEnabled(MainWnd.AppKey, AssemblyLocation);
            if (AutostartCbx.Checked && !autostartEnabled)
            {
                Autostart.SetAutoStart(MainWnd.AppKey, AssemblyLocation + " /silent");
            }
            else if (!AutostartCbx.Checked && autostartEnabled)
            {
                Autostart.UnSetAutoStart(MainWnd.AppKey);
            }

            // Change filters
            Filter.SetEnabledFilters(FiltersCbl.CheckedItems.OfType<string>().ToArray());

            // Close the options dialog
            Close();
        }

        private void EditFiltersBtn_Click(object sender, EventArgs e)
        {
            var dlg = new FiltersDlg();
            dlg.ShowDialog(this);

            InitForm();
        }

    }
}
